import feedparser, sgmllib, sys
from threading import Thread

if len(sys.argv) < 3:
	print 'Usage: ' + sys.argv[0] + ' <feeds file> <output file>'
	sys.exit(1)

feeds = []
fd = open(sys.argv[1], 'r')
for line in fd.readlines():
	feeds.append(line[:-1])
fd.close()

page = ''
fd = open('header.html', 'r')
for line in fd.readlines():
	page += line
fd.close()

months = ("January",
	"February",
	"March",
	"April",
	"May",
	"June",
	"July",
	"August",
	"September",
	"October",
	"November",
	"December")

class Stripper(sgmllib.SGMLParser):
	def __init__(self):
		sgmllib.SGMLParser.__init__(self)
		
	def strip(self, some_html):
		self.theString = ""
		self.feed(some_html)
		self.close()
		self.theString = self.theString.replace('<', '&lt;')
		self.theString = self.theString.replace('>', '&gt;')
		return self.theString.replace('/', '/&thinsp;')
		
	def handle_data(self, data):
		try:
			self.theString += data
		except UnicodeDecodeError:
			pass

class feedGrabber(Thread):
	def __init__(self, url):
		Thread.__init__(self)
		self.url = url
		self.feed = 0
	def run(self):
		self.feed = feedparser.parse(self.url)
		print >> sys.stderr, "Got feed: " + self.url

st = Stripper()
count = 0
page += " <div class=\"column\">"
allentries = []
grabberlist = []
for url in feeds:
	grabber = feedGrabber(url)
	grabberlist.append(grabber)
	grabber.start()

for grabber in grabberlist:
	grabber.join()
	allentries += grabber.feed.entries

print >> sys.stderr, "Sorting entries"
allentries.sort(key=lambda x: x.updated_parsed[:5], reverse=1)
onethird = len(allentries) / 3

print >> sys.stderr, "Building newspaper"
for entry in allentries:
	entryhtml = ""
	if(count >= onethird):
		page += " </div>"
		page += " <div class=\"column\">"
		count = 0

	hours = entry.updated_parsed[3]
	hours = hours - 7
	if hours < 0:
		hours += 12
	if entry.updated_parsed[4] < 10:
		minutes = '0' + str(entry.updated_parsed[4])
	else:
		minutes = str(entry.updated_parsed[4])
	if hours > 12:
		hours = hours - 12
		ampm = 'pm'
	else:
		ampm = 'am'
	hours = str(hours)
	date = months[entry.updated_parsed[1] - 1] + ' ' + str(entry.updated_parsed[2]) + ', ' + str(entry.updated_parsed[0]) + ' - ' + hours + ':' + minutes + ampm
	entryhtml += "  <span class=\"itemtitle\"><a href=\"" + entry.link + "\">" + entry.title + "</a></span>"
	entryhtml += "  <br /><span class=\"itemdate\">" + date + "</span>"
	entryhtml += "  <p>" + st.strip(entry.description) + "</p>"
	page += entryhtml.encode('utf-8', 'ignore')
	count += 1

page += " </div>"

fd = open('footer.html', 'r')
for line in fd.readlines():
	page += line
fd.close()

fd = open(sys.argv[2], 'w')
fd.write(page)
fd.close()
page
